//
//  EQMidCell.swift
//  DSP
//
//  Created by tucici on 2024/5/17.
//

import UIKit
import TCCKit
enum EQMidCellDirection{
    case up(String)
    case down(String)
}
protocol EQMidCellDelegate{
    func select(_ sign:SignModule)
}
class EQMidCell: UITableViewCell {
    private var bg_input: UIView!
    private var title_input: UILabel!
    private var input: UITextField!
    private var sub: UIButton!
    private var add: UIButton!
    private var line: UIView!
    private var slider : DSlider!
    private var collectionView : UICollectionView!
    var delegate : EQMidCellDelegate?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        backgroundColor = .clear
        selectionStyle = .none
        
        bg_input = UIView()
        bg_input.borderHexColor = HEX_BLACK
        bg_input.cornerRadius = 4.k_w
        bg_input.borderWidth = 1
        bg_input.backgroundColor = .clear
        
        title_input = UILabel()
        title_input.textHexColor = HEX_BLACK
        title_input.font = TCCKit.font(12,.bold)
        
        input = UITextField()
        input.delegate = self
        input.isUserInteractionEnabled = false
        input.borderHexColor = HEX_BLACK
        input.font = TCCKit.font(10)
        
        sub = UIButton(type: .custom)
        sub.setImage("-".img, for: .normal)
        sub.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        
        add = UIButton(type: .custom)
        add.setImage("+".img, for: .normal)
        add.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        
        slider = DSlider()
        slider.delegate = self
        slider.thumImg.image = UIImage(named: "slider_p")
      
        line = UIView()
        line.bgHexColor = HEX_BLACK
        
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .vertical
        flowlayout.minimumLineSpacing = 10.0.k_h
        flowlayout.minimumInteritemSpacing = floor(10.0.k_w)
        flowlayout.sectionInset = UIEdgeInsets(top: floor(4.k_h), left: 10.k_w, bottom: floor(5.k_h), right: 10.k_w)
        collectionView = UICollectionView(frame:.zero,collectionViewLayout:flowlayout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(InputItem.self)
        
        bg_input.addSubview(title_input)
        bg_input.addSubview(input)
        contentView.addSubview(sub)
        contentView.addSubview(add)
        contentView.addSubview(bg_input)
        contentView.addSubview(slider)
        contentView.addSubview(line)
        contentView.addSubview(collectionView)
        bg_input.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10.k_w)
            make.size.equalTo(CGSize(width: 80.k_w, height: 22.k_h))
            make.centerY.equalTo(slider)
        }
        
        title_input.snp.makeConstraints { make in
            make.right.equalTo(bg_input.snp.centerX)
            make.left.equalToSuperview().offset(5.k_w)
            make.centerY.equalToSuperview()
        }
        
        input.snp.makeConstraints { make in
            make.left.equalTo(bg_input.snp.centerX)
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().inset(4.k_w)
        }
    
        sub.snp.makeConstraints { make in
            make.left.equalTo(bg_input.snp.right).offset(5.k_w)
            make.size.equalTo(CGSize(width: 20.k_w, height: 20.k_w))
            make.centerY.equalTo(bg_input)
        }
        
        add.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(20.k_w)
            make.size.equalTo(CGSize(width: 20.k_w, height: 20.k_w))
            make.centerY.equalTo(bg_input)
        }
        
        slider.snp.makeConstraints { make in
            make.height.equalTo(floor(30.k_h))
            make.left.equalTo(sub.snp.right).offset(5.k_w)
            make.right.equalTo(add.snp.left).offset(-5.k_w)
            make.top.equalToSuperview()
        }
        
        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(10.k_w)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(0).priority(999)
            make.height.equalTo(0)
        }
    }
    
    var direction : EQMidCellDirection = .down("")
    var module : EQSwipeCellModule!
    var ch = ChannelModel(){
        didSet{
            array = Array(ch.signArray[module.r.location..<module.r.length])
        }
    }
    private var array = [SignModule](){
        didSet{
            guard let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else{return}
            let w = itemWidth(flowlayout, array.count)
            flowlayout.itemSize = CGSize(width: w, height: InputItemHeight)
            let h = collectionH(flowlayout, array, array.count)
            collectionView.reloadData()
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(h)
            }
            contentView.layoutIfNeeded()
            
            let temp = array.filter{$0.select}
            sign = (temp.count > 0 ? temp.first : array.first)!
        }
    }
    
    private var sign = SignModule(){
        didSet{
            updateUI()
        }
    }
    
    private func updateUI(){
        var down = false
        switch direction {
        case .up(let string):
            title_input.text = "\(string):"
            slider.minValue = 2.0
            slider.maxValue = 20.0
            input.text = String(format: "%0.1f", sign.quality)
            slider.currentValue = CGFloat(sign.quality)
            down = false
        case .down(let string):
            title_input.text = "\(string):"
            slider.minValue = 20
            slider.maxValue = 20000
            input.text = "\(Int(sign.frency))"
            slider.currentValue = CGFloat(sign.frency)
            down = true
        }
        
        slider.enable = sign.enable
        Tool.inputStatus(sign.enable, input)
        
        switch (sign.enable, sign.select){
        case (false, _):
            Tool.btnDisable(sub)
            Tool.btnDisable(add)
            
            bg_input.borderHexColor = HEX_BORDER_DISABLE
        case (true,_):
            Tool.btnNormal(sub)
            Tool.btnNormal(add)
            
            bg_input.borderHexColor = HEX_BLACK
        }
        
        
        collectionView.snp.updateConstraints { make in
            make.top.equalToSuperview().offset(down ? 1 : slider.bounds.height + 1)
            make.bottom.equalToSuperview().inset(down ? slider.bounds.height : 0).priority(999)
        }
        
        slider.snp.updateConstraints { make in
            make.top.equalToSuperview().offset(down ? collectionView.bounds.height + 1 : 1)
        }
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        switch direction{
        case .up:
            sign.quality = (sender == sub ? max(Float(slider.minValue), sign.quality - 0.1) : min(Float(slider.maxValue), sign.quality + 0.1))
        case .down:
            sign.frency = (sender == sub ? max(Int(slider.minValue), sign.frency - 1) : min(Int(slider.maxValue), sign.frency + 1))
        }
        delegate?.select(sign)
    }
}

//MARK: - DSliderDelgate
extension EQMidCell : DSliderDelgate{
    func valueForChange(_ sender: DSlider) {
        switch direction{
        case .up:
            sign.quality = Float(sender.currentValue)
        case .down:
            sign.frency = Int(sender.currentValue)
        }
        NotifyTool.post(updateChartStatus)
        updateUI()
    }
    
    func valueForChangeEnd(_ sender: DSlider) {
        delegate?.select(sign)
    }
}

extension EQMidCell : UITextFieldDelegate{
    
}

//MARK: - UICollectionViewDataSource
extension EQMidCell:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.cell(InputItem.self, indexPath) as! InputItem
        let sign = array[indexPath.row]
        cell.model = sign
        switch direction {
        case .up:
            cell.title.text = String(format: "%0.1f", sign.quality)
        case .down:
            cell.title.text = "\(Int(sign.frency))"
        }
        return cell
    }
}

//MARK: - UICollectionViewDelegate
extension EQMidCell:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let sign = array[indexPath.row]
        if sign.select || sign.enable == false {return}
        sign.select = true
        self.sign = sign
        delegate?.select(sign)
    }
}


